<script setup lang="ts">
  import { ref } from 'vue';
  import { Message } from '@arco-design/web-vue';
  import useModeModalHandler from '@/hooks/arco/useModeModalHandler';
  import { queryElderMedSchedule } from '@/api/medication-management/drug-plan';
  import { useSkeleton } from '@/hooks/arco/useSkeleton';
  import dayjs from 'dayjs';
  import Detail from './detail.vue';
  import ElderlySelect from '../components/elderly-select.vue';

  const weekArr = ref(['一', '二', '三', '四', '五', '六', '日']);
  // const dayArr = ref([]);

  const weekPage = ref(0);

  const detailHandler = useModeModalHandler();

  const monthArr = ref<any[]>([]);

  const today = dayjs().startOf('date');

  const todayIndex = ref(-1);

  const currentElder = ref<any>({});

  const planCalendarView = useSkeleton({
    immediate: false,
    apiFun: queryElderMedSchedule,
    onSuccess(data) {
      const monthMap = new Map<number, number>();

      todayIndex.value = -1;
      data.forEach((e: any, index: number) => {
        const currentDay = dayjs(e.scheduleDate);
        e.date = currentDay.date();

        const month = currentDay.month() + 1;

        if (today.isSame(currentDay)) {
          todayIndex.value = index;
        }

        let monthDay = 0;
        if (monthMap.get(month)) {
          monthDay = monthMap.get(month) as number;
        }
        monthMap.set(month, monthDay + 1);
      });

      const arr: any[] = [];

      monthMap.forEach((value, key) => {
        arr.push({
          month: key,
          dates: value,
        });
      });

      monthArr.value = arr;
    },
  });

  const showDetail = (
    date: string,
    schedule: any,
    record: any,
    week: string
  ) => {
    if (record.drugList && record.drugList.length > 0) {
      detailHandler.showDetail({
        elder: currentElder.value,
        scheduleData: record,
        date,
        schedule,
        week,
      });
    } else {
      Message.warning('暂无计划');
    }
  };

  const onElderChange = (e: any) => {
    // console.log('onElderChange', e);

    currentElder.value = e;

    if (e) {
      planCalendarView.execute({
        elderId: e.elderId,
        weekPage: weekPage.value,
      });
    }
  };

  const planTimeDate = [
    {
      name: '早',
    },
    {
      name: '中',
    },
    {
      name: '晚',
    },
    {
      name: '睡前',
    },
  ];

  const perviousWeek = () => {
    if (!currentElder.value) {
      return;
    }
    weekPage.value -= 1;
    planCalendarView.execute({
      elderId: currentElder.value.elderId,
      weekPage: weekPage.value,
    });
  };

  const nextWeek = () => {
    if (!currentElder.value) {
      return;
    }
    weekPage.value += 1;
    planCalendarView.execute({
      elderId: currentElder.value.elderId,
      weekPage: weekPage.value,
    });
  };

  const goToToday = () => {
    if (!currentElder.value) {
      return;
    }
    weekPage.value = 0;
    planCalendarView.execute({
      elderId: currentElder.value.elderId,
      weekPage: weekPage.value,
    });
  };

  let timeDate: any;
</script>

<template>
  <div class="flex flex-row gap-5 full-h-wrapper">
    <Detail v-bind="detailHandler.bindProps" />

    <ElderlySelect @change="onElderChange" />

    <div
      v-if="currentElder && currentElder.elderId"
      class="flex-1 h-full overflow-y-auto py-2 px-4 border rounded shadow"
    >
      <div class="flex justify-between mb-2">
        <a-space>
          <h2 class="text-lg font-medium tracking-wide">用药计划</h2>
          <a-button :disabled="weekPage === 0" size="mini" @click="goToToday">
            今天
          </a-button>
        </a-space>
        <a-space class="self-end mt-1">
          <a-button type="primary" @click="perviousWeek">
            <div class="flex items-center">
              <icon-left />
              <span>上一周</span>
            </div>
          </a-button>
          <a-button type="primary" @click="nextWeek">
            <div class="flex items-center">
              <span>下一周</span>
              <icon-right />
            </div>
          </a-button>
        </a-space>
      </div>
      <skeleton-view v-slot="{ data }" v-bind="planCalendarView.bindProps">
        <table class="plan-table">
          <colgroup>
            <col style="width: 8%" />
            <col v-for="item in 7" :key="item" style="width: 13%" />
          </colgroup>

          <thead>
            <tr>
              <th rowspan="2">/</th>
              <th
                v-for="(monthItem, index) in monthArr"
                :key="index"
                :colspan="monthItem.dates"
                class="month-day py-3"
              >
                <span>{{ monthItem.month }}月</span>
              </th>
            </tr>
            <tr>
              <th
                v-for="(date, index) in data"
                :key="index"
                :class="[
                  'py-3',
                  {
                    'is-today': todayIndex === index,
                    '!border-r-transparent': index < data.length - 1,
                  },
                ]"
              >
                <div class="flex flex-col items-center">
                  <span class="date-text">
                    {{ date.date }}
                  </span>
                  <span class="mt-1 week-text">{{ weekArr[index] }}</span>
                </div>
              </th>
            </tr>
          </thead>

          <tbody>
            <tr v-for="(timeType, timeIndex) in planTimeDate" :key="timeIndex">
              <td class="time-type">{{ timeType.name }}</td>
              <td
                v-for="(dateItem, dayIndex) in data"
                :key="dayIndex"
                :class="['plan-item-td cursor-pointer']"
                @click="
                  showDetail(
                    dateItem.scheduleDate,
                    timeType,
                    dateItem.medSchduleList[timeIndex],
                    weekArr[timeIndex]
                  )
                "
              >
                {{ void (timeDate = dateItem.medSchduleList[timeIndex]) }}
                <div
                  v-if="timeDate.drugList && timeDate.drugList.length > 0"
                  class="plan-item flex flex-col"
                >
                  <div :class="['tag']">
                    {{ timeDate.statusLabel }}
                  </div>
                  <!-- TODO: 药物使用状态 -->
                  <div
                    v-for="(medItem, medIndex) in timeDate.drugList"
                    :key="medIndex"
                    class="med-item"
                  >
                    <span class="text-clamp">{{ medItem.drugName }}</span>
                  </div>
                </div>
                <div v-else class="w-full text-center"> 无计划 </div>
              </td>
            </tr>
          </tbody>
        </table>
      </skeleton-view>
    </div>
    <div
      v-else
      class="flex-1 overflow-y-hidden h-full py-2 px-4 border rounded shadow flex justify-center items-center"
    >
      <a-empty>
        <template #image>
          <icon-empty size="100" />
        </template>
        <span class="text-xl">请选择长者</span>
      </a-empty>
    </div>
  </div>
</template>

<style lang="less" scoped>
  .text-clamp {
    width: 100%;
    line-clamp: 2; /* 限制显示的行数为2 */
    overflow: hidden; /* 隐藏溢出的文本 */
    text-overflow: ellipsis; /* 用省略号表示溢出的文本 */
  }

  .plan-table {
    border-spacing: 0;
    border-collapse: collapse;
    border: 1px solid #e5e5e5;
    width: 100%;

    th,
    td {
      border: 1px solid #e5e5e5;
      padding: 4px 4px;
    }

    .plan-item-td {
      padding: 0;
      height: 120px;
    }

    .time-type {
      text-align: center;
      height: 120px;
    }

    .date-text {
      width: 36px;
      height: 36px;
      text-align: center;
      border-radius: 50%;
      background-color: #e5e5e5;
      color: #333333;
      font-size: 18px;
      align-content: center;
    }

    .month-day {
      color: #666666;
      font-size: 14px;
      font-weight: 400;
    }

    .week-text {
      color: #666666;
      font-weight: 400;
    }

    .is-today .date-text {
      background-color: rgb(var(--primary-1));
      color: rgb(var(--primary-6));
    }

    .plan-item {
      height: 100%;
      width: 100%;
      position: relative;
      overflow: hidden;
      padding: 16px 4px 4px;
      .tag {
        font-size: 12px;
        text-align: center; // 文本居中
        position: absolute; // 绝对定位
        top: 6px;
        right: -20px;
        // 以下属性会影响斜边标签的显示
        padding: 4px 20px;
        line-height: 1;
        transform: rotate(40deg);
      }

      .status-1 {
        background-color: #f7f8fa;
        color: #86909c;
      }

      .status-2 {
        background-color: #e8f7ff;
        color: #3491fa;
      }

      .status-3 {
        background-color: #e8ffea;
        color: #00b42a;
      }

      .status-4 {
        background-color: #ffece8;
        color: #f53f3f;
      }
    }
  }
</style>
